package cm.lock.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

// 与该注解联合使用@Cacheable(cacheNames = "缓存名称", key = "redis中的key")
//@EnableCaching
//// 标识该类为一个配置类
//@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.database:0}")
    private int database;

    @Autowired
    private LettuceConnectionFactory lettuceConnectionFactory;

    @Bean
    @ConditionalOnMissingBean
    public RedisTemplate<String,Object> redisTemplate(){
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        template.setKeySerializer(stringRedisSerializer());
        template.setHashKeySerializer(stringRedisSerializer());
        template.setValueSerializer(fastJsonSerializer());
        template.setHashValueSerializer(fastJsonSerializer());
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public FastJsonSerializer fastJsonSerializer(){
        return new FastJsonSerializer();
    }


    @Bean
    @ConditionalOnMissingBean
    public StringRedisSerializer stringRedisSerializer(){
        return new StringRedisSerializer();
    }

    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate stringRedisTemplate(){
        StringRedisTemplate template = new StringRedisTemplate(lettuceConnectionFactory);
        return template;
    }

}

